package cn.fl.product.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.riskctrl.facade.brjf.api.IBrjfTelCheckApiService;
import fl.riskctrl.facade.py.api.IPyExecutiveApiService;
import fl.riskctrl.facade.py.api.IPyTelCheckApiService;
import fl.riskctrl.facade.riskctrl.dto.DataResultDTO;
import fl.riskctrl.facade.td.api.ITdTelCheckApiService;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.spl.dto.SplBiApplyRlPsnDTO;
import fl.spl.facade.spl.dto.SplInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.npspl.service.ISplNpSocialRlService;
import cn.fl.npspl.vo.SplNpSocialRlVO;
import cn.fl.product.service.ISplRlPsnService;
import cn.fl.product.transform.SplRlPsnVOTransform;
import cn.fl.product.vo.SplRlPsnVO;
import fl.spl.facade.spl.api.ISplInfoApiService;
import fl.spl.facade.spl.api.ISplInfoApplyModifyApiService;
import fl.spl.facade.spl.condition.SplRlPsnQueryCondition;
import fl.spl.facade.spl.dto.SplRlPsnDTO;

/**
 * @Description: 供应商关联人员信息表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class SplRlPsnServiceImpl implements ISplRlPsnService {

	/**
	 * 供应商 API 暴露服务
	 */
	@Autowired
	private ISplInfoApiService splInfoApiService;
	
	/**
	 * 百融三要素核查
	 * */
	@Autowired
	private IBrjfTelCheckApiService brjfTelCheckApiService ;
	/**
	 * 鹏元三要素核查
	 * */
	@Autowired
	private IPyTelCheckApiService pyTelCheckApiService ;
	/**
	 * 同盾三要素核查
	 * */
	@Autowired
	private ITdTelCheckApiService tdTelCheckApiService ;
	/**
	 * 鹏元企业信息核查
	 * */
	@Autowired
	private IPyExecutiveApiService pyExecutiveApiService ;
	/**
	 * 本地数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	@Autowired
	ISplInfoApplyModifyApiService splInfoApplyModifyApiService;
	
	@Autowired
	private ISplNpSocialRlService splNpSocialRlService;

	@Override
	public SplRlPsnVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.newWebLogger("根据主键查询供应商联系人信息失败,主键参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001,BaseExceptionConstant.COMMON_0001_NAME);
		}
		SplRlPsnDTO dto = this.splInfoApiService.selectPrdSplRlPsnById(id, CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		return SplRlPsnVOTransform.toVO(dto);
	}

	@Override
	public Long add(SplRlPsnVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.newWebLogger("新增供应商联系人失败,供应商联系人对象参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001,BaseExceptionConstant.COMMON_0001_NAME);
		}
		return this.splInfoApiService.addPrdSplRlPsn(SplRlPsnVOTransform.toDTO(entity));
	}

	/*@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id))return false;
		return this.prdSplRlPsnApiService.removeById(id);
	}*/

	@Override
	public boolean modify(SplRlPsnVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.newWebLogger("修改供应商联系人失败,供应商联系人对象参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001,BaseExceptionConstant.COMMON_0001_NAME);
		}
		return this.splInfoApiService.modifyPrdSplRlPsn(SplRlPsnVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		page = this.splInfoApiService.searchPrdSplRlPsnListPage(page, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		@SuppressWarnings("unchecked")
		List<SplRlPsnDTO> resultList = (List<SplRlPsnDTO>) page.getResultList();
		page.setResultList(SplRlPsnVOTransform.toVOList(resultList));
		return page;
				
	}

	@Override
	public Pager searchListPageWithEncrypt(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
		page = this.splInfoApiService.searchPrdSplRlPsnListPageWithEncrypt(page, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		@SuppressWarnings("unchecked")
		List<SplRlPsnDTO> resultList = (List<SplRlPsnDTO>) page.getResultList();
		page.setResultList(SplRlPsnVOTransform.toVOList(resultList));
		return page;

	}

	@Override
	public List<KeyValueVO> searchCertTypCdList() throws BaseException{
		return this.getKvList(DictionaryConstant.CODE_GRP_CERT_TYP_CD);
	}
	
	@Override
	public List<KeyValueVO> searchRlTypCdList() throws BaseException{
		return this.getKvList(DictionaryConstant.CODE_RL_TYP_CD);
	}
	
	/**
	 * 根据字典中代码组值获取组员集合
	 * @param grpCd 代码组值
	 * @return 集合
	 */
	public List<KeyValueVO> getKvList(String grpCd){
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
				for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysDictionaryDTO.getCode());
					keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
					kvList.add(keyValueVO);
				}
			}
		} catch (BaseException e) {
			BaseLogUtils.newWebLogger("获取字典项组失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
		} catch (Exception e) {
			BaseLogUtils.newWebLogger("获取字典项组失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return kvList;
	}

	@Override
	public List<SplRlPsnVO> searchList(SplRlPsnQueryCondition qc) {
		if(null==qc){
			return null;
		}
		return SplRlPsnVOTransform.toVOList(this.splInfoApiService.searchPrdSplRlPsnList(qc,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException {
		if(CollectionUtils.isEmpty(ids)){
			throw new BaseException(BaseExceptionConstant.COMMON_0001, BaseExceptionConstant.COMMON_0001_NAME);
		}
		return this.splInfoApiService.removePrdSplRlPsnByIds(ids);
	}

	@Override
	public DataResultDTO checkRlPsn(Map<String, String> map) throws BaseException {
		// TODO Auto-generated method stub
		DataResultDTO resultDTO = new DataResultDTO(BaseConstant.IS_YESNO_YES,"成功");
		if(CollectionUtils.isMapEmpty(map)){
			resultDTO.setInfo("数据为空");
			resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
			return resultDTO ;
		}
		Long dataId ;
		if(StringUtils.isNotEmpty(map.get("rlId")) && !"null".equals(map.get("rlId"))){
			dataId = Long.valueOf(map.get("rlId"));
		}else if(StringUtils.isNotEmpty(map.get("applyPsnId"))){
			dataId = Long.valueOf(map.get("applyPsnId"));
		}else{
			resultDTO.setInfo("数据ID为空");
			resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
			return resultDTO ;
		}
		String code ;
		String splAttrCd = map.get("splAttrCd");
		SplRlPsnDTO splRlPsnDTO = new SplRlPsnDTO();
		SplBiApplyRlPsnDTO applyRlPsnDTO = new SplBiApplyRlPsnDTO();
		if("verify".equals(map.get("type"))){
			SplInfoDTO splDTO = this.splInfoApiService.selectSplInfoById(Long.valueOf(map.get("splId")));
			if("5".equals(map.get("rlTypCd"))){
				resultDTO = this.pyExecutiveApiService.getPersonShareholderInfoCheck(dataId, map.get("certNo"), map.get("rlNm"), splDTO.getSplNm(), null);
			}else{
				resultDTO = this.pyExecutiveApiService.getPersonArtificialInfoCheck(dataId, map.get("certNo"), map.get("rlNm"), splDTO.getSplNm(), null);
			}
			
			if(resultDTO != null && resultDTO.getSuccess() == 1){
				code = (String)resultDTO.getData();
				if("一致".equals(code)){
					splRlPsnDTO.setBusInfoVerify("1");
					applyRlPsnDTO.setBusInfoVerify("1");
				}else{
					splRlPsnDTO.setBusInfoVerify("-1");
					applyRlPsnDTO.setBusInfoVerify("-1");
				}
			}else{
				splRlPsnDTO.setBusInfoVerify("0");
				applyRlPsnDTO.setBusInfoVerify("0");
			}
		}
		if("TD".equals(map.get("type"))){
			resultDTO = this.tdTelCheckApiService.getTDTelCheck(dataId, map.get("certNo"), map.get("rlNm"), map.get("tel"));
			if(resultDTO != null && resultDTO.getSuccess() == 1){
				code = (String)resultDTO.getData();
				if("一致".equals(code)){
					splRlPsnDTO.setTdPerVerify("1");
					applyRlPsnDTO.setTdPerVerify("1");
				}else{
					splRlPsnDTO.setTdPerVerify("-1");
					applyRlPsnDTO.setTdPerVerify("-1");
				}
			}else{
				splRlPsnDTO.setTdPerVerify("0");
				applyRlPsnDTO.setTdPerVerify("0");
			}
		}
		if("PY".equals(map.get("type"))){
			resultDTO = this.pyTelCheckApiService.getPYTelCheck(dataId, map.get("certNo"), map.get("rlNm"), map.get("tel"));
			if(resultDTO != null && resultDTO.getSuccess() == 1){
				code = (String)resultDTO.getData();
				if("一致".equals(code)){
					splRlPsnDTO.setPyPerVerify("1");
					applyRlPsnDTO.setPyPerVerify("1");
				}else{
					splRlPsnDTO.setPyPerVerify("-1");
					applyRlPsnDTO.setPyPerVerify("-1");
				}
			}else{
				splRlPsnDTO.setPyPerVerify("0");
				applyRlPsnDTO.setPyPerVerify("0");
			}
		}
		if("BR".equals(map.get("type"))){
			resultDTO = this.brjfTelCheckApiService.getBRJFTelCheck(dataId, map.get("certNo"), map.get("rlNm"), map.get("tel"),null);
			if(resultDTO != null && resultDTO.getSuccess() == 1){
				code = (String)resultDTO.getData();
				if("均一致".equals(code)){
					splRlPsnDTO.setBrPerVerify("1");
					applyRlPsnDTO.setBrPerVerify("1");
				}else{
					splRlPsnDTO.setBrPerVerify("-1");
					applyRlPsnDTO.setBrPerVerify("-1");
				}
			}else{
				splRlPsnDTO.setBrPerVerify("0");
				applyRlPsnDTO.setBrPerVerify("0");
			}
		}
		boolean b = false;
		if(StringUtils.isEmpty(map.get("applyPsnId"))){
			if ("1".equals(splAttrCd)) {
				SplNpSocialRlVO npSocialRlVO = new SplNpSocialRlVO();
				npSocialRlVO.setPyPerVerify(splRlPsnDTO.getPyPerVerify());
				npSocialRlVO.setTdPerVerify(splRlPsnDTO.getTdPerVerify());
				npSocialRlVO.setBrPerVerify(splRlPsnDTO.getBrPerVerify());
				npSocialRlVO.setId(Long.valueOf(map.get("rlId")));
				npSocialRlVO.setMdfTm(new Date());
				npSocialRlVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				b = this.splNpSocialRlService.modify(npSocialRlVO);
			} else {
				splRlPsnDTO.setId(Long.valueOf(map.get("rlId")));
				splRlPsnDTO.setMdfTm(new Date());
				splRlPsnDTO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				BaseLogUtils.newWebLogger("修改变更中联系人三元素校验信息").setLogOperType(LogOperEnum.REQ)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.setKeys("splRlPsnDTO", JSON.toJSONString(splRlPsnDTO))
						.info();
				b = this.splInfoApiService.modifyPrdSplRlPsn(splRlPsnDTO);
			}
			
		}else{
			applyRlPsnDTO.setId(Long.valueOf(map.get("applyPsnId")));
			applyRlPsnDTO.setMdfTm(new Date());
			applyRlPsnDTO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			BaseLogUtils.newWebLogger("修改变更中联系人三元素校验信息").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setKeys("applyRlPsnDTO", JSON.toJSONString(applyRlPsnDTO))
					.info();
			b = splInfoApplyModifyApiService.modifyBiApplyRlPsn(applyRlPsnDTO);
		}
		if(b){
			BaseLogUtils.newWebLogger("修改联系人信息成功").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
		}else{
			BaseLogUtils.newWebLogger("修改联系人信息失败").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		}
		return resultDTO;
	}

	@Override
	public boolean modifyRlPsnVerify(String splId) throws BaseException {
		boolean b = false ;
		if(StringUtils.isEmpty(splId)){
			BaseLogUtils.newWebLogger("供应商ID为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			return b ;
		}
		try{
		SplRlPsnQueryCondition qc = new SplRlPsnQueryCondition();
		
		qc.setSplId(Long.valueOf(splId));
		// TODO Auto-generated method stub
		List<SplRlPsnDTO> rlPsnList = this.splInfoApiService.searchPrdSplRlPsnList(qc , CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		if(CollectionUtils.isNotEmpty(rlPsnList)){
			for (SplRlPsnDTO splRlPsnDTO : rlPsnList) {
				splRlPsnDTO.setBrPerVerify("2");
				splRlPsnDTO.setTdPerVerify("2");
				splRlPsnDTO.setPyPerVerify("2");
				splRlPsnDTO.setBusInfoVerify("2");
			}
			b = this.splInfoApiService.batchAddOrModifySplRlPsn(rlPsnList);
		}
		}catch(BaseException e){
			BaseLogUtils.newWebLogger("修改联系人三元素校验结果失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
		}catch(Exception e){
			BaseLogUtils.newWebLogger("修改联系人三元素校验结果失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return b;
	}
}
;